package com.android.bookgarden.utli;

import android.content.Context;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 处理选择图片和拍照的
 */
public class FileFactory {
    private FileFactory() {
    }

    private static String createImageFileName() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        return imageFileName;
    }

    public static File createTempImageFile(@NonNull Context context) {
        try {
            File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            File image = File.createTempFile(
                    FileFactory.createImageFileName(),  /* prefix */
                    ".jpeg",         /* suffix */
                    storageDir      /* directory */
            );
            return image;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static File createImageFile(@NonNull Context context, @NonNull String fileName) {
        try {
            if (TextUtils.isEmpty(fileName)) {
                fileName = "0000";
            }
            File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            File image = new File(storageDir, fileName + ".jpeg");
            if (!image.exists()) {
                image.createNewFile();
            } else {
                image.delete();
                image.createNewFile();
            }
            return image;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] readBytesFromFile(@NonNull File file) {
        try (InputStream inputStream = new FileInputStream(file)) {
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            return bytes;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
